package com.example.demo.web.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SysSecurityConfig extends WebSecurityConfigurerAdapter {

    //密码加密方式
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
       return new BCryptPasswordEncoder();
    }

    @Autowired
    MyUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers( "/static/**","/templates/**","/login","/swagger-ui/**","/swagger-resources/**","/v2/**").permitAll()
//                .antMatchers( "/**","/**/**").permitAll()
                .anyRequest().authenticated() // 没有定义的请求，所有的角色都可以访问（tmp也可以）。
                .and()
                .headers()
                .frameOptions()//frame页面的地址只能为同源域名下的页面
                .disable()
                .and()
                .formLogin()//表单登录
                .loginPage("/login")//登录页面  前后端分离不需要指定登录页面
                .loginProcessingUrl("/login")//登录请求处理接口
//                .usernameParameter("")//用户名参数名字
//                .passwordParameter("")//密码
                .defaultSuccessUrl("/loginHandler/success")//登录成功跳转请求
                .failureForwardUrl("/loginHandler/fail")//登录失败跳转请求
                .and()
                .csrf()//跨域
                .disable()
                .httpBasic();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/**");
    }

}
